package yxy.game.pm2.module.therionHunting;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import yxy.apple.logger.Logger;
import yxy.apple.util.ActiveUtil;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.therionboss;
import yxy.cherry.data.bean.therionrankreward;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.area.AreaGroupBean;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.module.mail.MailHandle;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.stat.StatHandle;
import yxy.game.pm2.module.task.TaskHandle;

import java.util.*;

/**
 * @author wrs
 * @name TherionHandle
 * @description
 * @since 2022-06-09
 */
public class TherionFutureHandle {

    protected static Logger logger = Logger.create(TherionFutureHandle.class);

    /**
     * 本服刷新
     *
     * @param areaBean
     */
    public void areaBeanUpdate(AreaBean areaBean) {
        try {
            int day = DateTime.now().getDayOfWeek();
            ArrayList<Integer> areaIdList = new ArrayList<>();
            areaIdList.add(areaBean.getAreaId());

            for (Integer therionType : getAllTherionType()) {
                TherionModule therionModule = TherionModule.get(TherionModule.THERION_LOCAL, areaBean.getAreaId(), therionType);

                update(therionModule, TherionModule.THERION_LOCAL, therionType, areaBean.getAreaId());

                //没有开启就不执行后续方法
                if (!ArrayUtils.contains(therionModule.getConditions(), day)) {
                    continue;
                }

                //神兽的所有挑战位
                Map<Integer, TherionChallengingPosition> positionMap = TherionChallengingPosition.getAll(TherionModule.THERION_LOCAL, areaBean.getAreaId(), therionType);
                handleTherionModule(areaBean.getAreaId(), TherionModule.THERION_LOCAL, therionType, therionModule, positionMap);
                //更新神兽信息  查看神兽是否复活
                TherionModule.update(TherionModule.THERION_LOCAL, areaBean.getAreaId(), therionType,areaIdList);
            }
        } catch (RedisException e) {
            e.printStackTrace();
        }


    }

    /**
     * 跨服刷新
     *
     * @param areaGroupBean
     */
    public void areaGroupBeanUpdate(AreaGroupBean areaGroupBean) {
        try {
            int day = DateTime.now().getDayOfWeek();
            ArrayList<Integer> areaIdList = new ArrayList<>();
            ArrayList<String> areaList = areaGroupBean.getAreaList();
            for (int i = 0; i < areaList.size(); i++) {
                areaIdList.add(Integer.parseInt(areaList.get(i)));
            }

            for (Integer therionType : getAllTherionType()) {
                TherionModule therionModule = TherionModule.get(TherionModule.THERION_CROSS, areaGroupBean.getGroupId(), therionType);

                update(therionModule, TherionModule.THERION_CROSS, therionType, areaGroupBean.getGroupId());

                //没有开启就不执行后续方法
                if (!ArrayUtils.contains(therionModule.getConditions(), day)) {
                    continue;
                }
                //神兽的所有挑战位
                Map<Integer, TherionChallengingPosition> positionMap = TherionChallengingPosition.getAll(TherionModule.THERION_CROSS, areaGroupBean.getGroupId(), therionType);
                handleTherionModule(areaGroupBean.getGroupId(), TherionModule.THERION_CROSS, therionType, therionModule, positionMap);
                //更新神兽信息  查看神兽是否复活
                TherionModule.update(TherionModule.THERION_LOCAL, areaGroupBean.getGroupId(), therionType,areaIdList);
            }
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 世界刷新
     *
     * @param areaGroupBean
     */
    public void worldBeanUpdate(AreaGroupBean areaGroupBean) {
        try {
            int day = DateTime.now().getDayOfWeek();
            ArrayList<Integer> areaIdList = new ArrayList<>();
            ArrayList<String> areaList = areaGroupBean.getAreaList();
            for (int i = 0; i < areaList.size(); i++) {
                areaIdList.add(Integer.parseInt(areaList.get(i)));
            }

            for (Integer therionType : getAllTherionType()) {
                TherionModule therionModule = TherionModule.get(TherionModule.THERION_WORLD, areaGroupBean.getGroupId(), therionType);

                update(therionModule, TherionModule.THERION_WORLD, therionType, areaGroupBean.getGroupId());

                //没有开启就不执行后续方法
                if (!ArrayUtils.contains(therionModule.getConditions(), day)) {
                    continue;
                }
                //神兽的所有挑战位
                Map<Integer, TherionChallengingPosition> positionMap = TherionChallengingPosition.getAll(TherionModule.THERION_WORLD, areaGroupBean.getGroupId(), therionType);
                handleTherionModule(areaGroupBean.getGroupId(), TherionModule.THERION_WORLD, therionType, therionModule, positionMap);
                //更新神兽信息  查看神兽是否复活
                TherionModule.update(TherionModule.THERION_WORLD, areaGroupBean.getGroupId(), therionType,areaIdList);
            }
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }


    /**
     * 神兽战斗界面信息处理
     *
     * @param areaIdOrGroupId 服ID 或 战区ID
     * @param gameType        玩法类型
     * @param therionType     神兽类型
     * @param therionModule   神兽Module
     * @param positionMap     神兽的所有挑战位
     */
    private void handleTherionModule(int areaIdOrGroupId, int gameType, int therionType, TherionModule therionModule, Map<Integer, TherionChallengingPosition> positionMap) {

        try {

            logger.info("神兽战斗界面信息处理:玩法类型:%s,%s服,神兽类型:%s,时间:%s", gameType, areaIdOrGroupId, therionType, DateTime.now().toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")));

            //如果神兽死亡且发过奖励了  就不再进行操作
            if (therionModule.getStatus() == 3 && !therionModule.isNeedSettle()) {
                return;
            }

            //查询排行榜上对神兽的总伤害
            long rankTotalDamage = 0;
            switch (gameType) {
                case TherionModule.THERION_LOCAL:
                    AreaBean areaBean = AreaBean.get(areaIdOrGroupId);
                    AreaRankTherionChallege areaRank = AreaRankTherionChallege.getRank(areaBean, therionType);//本服
                    for (RankEntry entry : areaRank.all()) {
                        if (entry != null) {
                            Long damage = entry.getValue();
                            rankTotalDamage += damage;
                        }
                    }
                    break;
                case TherionModule.THERION_CROSS:
                    AreaGroupBean areaGroupBean = AreaGroupBean.get(areaIdOrGroupId);
                    AreaGroupRankTherionChallege areaGroupRank = AreaGroupRankTherionChallege.getRank(areaGroupBean, therionType);//跨服
                    for (RankEntry entry : areaGroupRank.all()) {
                        if (entry != null) {
                            Long damage = entry.getValue();
                            rankTotalDamage += damage;
                        }
                    }
                    break;
                case TherionModule.THERION_WORLD:
                    areaGroupBean = AreaGroupBean.get(areaIdOrGroupId);
                    WorldRankTherionChallege worldRank = WorldRankTherionChallege.getRank(areaGroupBean, therionType);//世界
                    for (RankEntry entry : worldRank.all()) {
                        if (entry != null) {
                            Long damage = entry.getValue();
                            rankTotalDamage += damage;
                        }
                    }
                    break;
                default:
                    return;
            }

            //查询所有非空挑战位上对神兽的总伤害
            long positionTotalDamage = 0;
            for (TherionChallengingPosition position : positionMap.values()) {
                if (position.getPlayCode() != null) {
                    long damage = TherionHandle.calculateDamage(position.getPlayCode(), gameType, therionType);
                    positionTotalDamage += damage;
                }
            }

            //如果没有打就不执行后续代码
            if (rankTotalDamage + positionTotalDamage == 0) return;

            //根据伤害减少神兽血量
            if (rankTotalDamage + positionTotalDamage > therionModule.getLife()) {
                //当前的那只神兽信息
                therionboss boss = DataCenter.getData(therionModule.getId(), therionboss.class);
                String[] hours = boss.getSpawntime().split(",");

                //神兽死亡
                therionModule.setLife(0);
                therionModule.setStatus(3); //复活中
                therionModule.setOpen(false);
                therionModule.setNeedSettle(false);
                TherionHandle.setTherionModuleResurrectTime(hours, therionModule, gameType, boss);//重生倒计时
                therionModule.set(gameType, therionType, areaIdOrGroupId);

                //添加排行榜上玩家的玩法挑战记录

                RankModule rankModule = getRankModule(gameType, areaIdOrGroupId, therionType);
                for (String pCode : rankModule.allKeys()) {
                    TherionPlayerModule playerModule = TherionPlayerModule.get(pCode);
                    HashMap<Integer, TherionChallengeRecord> recordHashMap = playerModule.getChallengeRecords().get(gameType);
                    RankEntry entry = rankModule.get(pCode);
                    int rank = 0; //排名
                    long damage = 0;//玩家总伤害
                    if (entry != null) {
                        rank = rankModule.rank(pCode);
                        damage = entry.getValue();
                    }
                    TherionChallengeRecord challengeRecord = new TherionChallengeRecord();
                    challengeRecord.setTheronId(therionModule.getId());
                    challengeRecord.setTherionName(therionModule.getName());
                    challengeRecord.setRank(rank);
                    challengeRecord.setTotalValue(damage);
                    challengeRecord.setDate(DateTime.now());
                    recordHashMap.put(therionType, challengeRecord);
                    playerModule.set(pCode);
                }


                if (gameType == TherionModule.THERION_WORLD) {
                    Currencies rewards = new Currencies(Currency.create(boss.getRewardtype(), boss.getRewardid(), boss.getRewardnumber())); //奖励
                    TherionChallengingPosition position = TherionChallengingPosition.get(gameType, areaIdOrGroupId, therionType, 101);
                    String title = GameString.神兽击杀奖励_title(TherionModule.getGameName(gameType), therionModule.getName()).getText();
                    String content = GameString.神兽击杀奖励_msg(TherionModule.getGameName(gameType), therionModule.getName()).getText();
                    //邮件发送奖励
                    new MailHandle().sendMail(position.getPlayCode(), MailTypeEnum.Mail, title, content, CCReason.神兽, rewards);
                }

                //todo 排行榜奖励发放、清空；挑战位清空  玩家挑战冷却时间清空，双倍奖励
                //挑战位清空
                TherionChallengingPosition.removeAllFromRedis(gameType, areaIdOrGroupId, therionType);

                int rank = 0;
                long damage = 0;

                JSONArray playerCodeArrary1 = new JSONArray();
                JSONArray playerCodeArrary2 = new JSONArray();
                JSONArray RankArrary1 = new JSONArray();
                JSONArray RankArrary2 = new JSONArray();
                JSONArray ValueArrary = new JSONArray();

                for (String playerCode : rankModule.allKeys()) {

                    RankEntry entry = rankModule.get(playerCode);
                    if (entry != null) {
                        rank = rankModule.rank(playerCode); //排名
                        damage = entry.getValue();//玩家总伤害

                        //todo 记录
                        playerCodeArrary1.add(playerCode);
                        RankArrary1.add(rank);
                        ValueArrary.add(damage);
                    }

                    if (rank <= 100) {//10名前有奖励(2022.7.11 改成表中有数据的都发)

                        //todo 记录
                        playerCodeArrary2.add(playerCode);
                        RankArrary2.add(rank);

                        //奖励
                        Map<String, therionrankreward> allData = DataCenter.getAllData(therionrankreward.class);
                        therionrankreward therionrankreward = null;
                        for (therionrankreward value : allData.values()) {
                            if (value.getType() == gameType && TherionHandle.getTherionKey(value.getTheriontype()) == therionType && rank >= value.getRankingmin() && rank <= value.getRankingmax()) {
                                therionrankreward = value;
                                break;
                            }
                        }
                        //奖励
                        DateTime now = DateTime.now();
                        long time17_55 = ActiveUtil.time17_55(now).getMillis();
                        long time19_05 = ActiveUtil.time19_05(now).getMillis();
                        long time11_55 = ActiveUtil.time11_55(now).getMillis();
                        long time13_05 = ActiveUtil.time13_05(now).getMillis();
                        int times = (now.getMillis() >= time11_55 && now.getMillis() <= time13_05) || (now.getMillis() >= time17_55 && now.getMillis() <= time19_05) ? 2 : 1;


                        Currencies rewards = new Currencies(Currency.create(therionrankreward.getRewardtype(), therionrankreward.getRewardid(), therionrankreward.getRewardnum()));
                        String title = GameString.神兽伤害奖励_title(TherionModule.getGameName(gameType), therionModule.getName()).getText();
                        String content = GameString.神兽伤害奖励_msg(TherionModule.getGameName(gameType), therionModule.getName(), damage, rank).getText();
                        //邮件发送奖励
                        if (times == 2 && gameType == TherionModule.THERION_WORLD) rewards.add(rewards);
                        new MailHandle().sendMail(playerCode, MailTypeEnum.Mail, title, content, CCReason.神兽, rewards);
                    }

                    //神兽争夺累计+1
                    TaskHandle.handle(playerCode, TaskType.统计型_神兽玩法参与_次数, 1);

                    //玩家挑战冷却时间清空
                    TherionPlayerModule playerModule = TherionPlayerModule.get(playerCode);
                    playerModule.getCoolDown().put(gameType, new HashMap<>());
                    playerModule.set(playerCode);
                }

                //todo 神兽记录
                StatHandle.stat_神兽挑战记录(TherionModule.getName(therionType), gameType, playerCodeArrary1.toString(), RankArrary1.toString(), ValueArrary.toString());
                StatHandle.stat_神兽奖励发放记录(TherionModule.getName(therionType), gameType, playerCodeArrary2.toString(), RankArrary2.toString());

                //排行榜清空
                rankModule.clear();

            } else {
                //神兽未死亡，当前血量 - 伤害值
                therionModule.setLife(therionModule.getLife() - (rankTotalDamage + positionTotalDamage));
            }
            therionModule.set(gameType, therionType, areaIdOrGroupId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有神兽类型
     */
    private static ArrayList<Integer> getAllTherionType() {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(TherionModule.TSINGLUNG);
        list.add(TherionModule.WHITETIGER);
        list.add(TherionModule.ROSEFINCH);
        list.add(TherionModule.BASALTIC);
        return list;
    }

    /**
     * 获取某个排行榜（本服、跨服、世界）
     *
     * @param gameType
     * @param areaIdOrGroupId 服ID 或 战区ID
     * @param therionType
     */
    public static RankModule getRankModule(int gameType, int areaIdOrGroupId, int therionType) {
        switch (gameType) {
            case TherionModule.THERION_LOCAL:
                AreaBean areaBean = AreaBean.get(areaIdOrGroupId);
                return AreaRankTherionChallege.getRank(areaBean, therionType);
            case TherionModule.THERION_CROSS:
                AreaGroupBean areaGroupBean = AreaGroupBean.get(areaIdOrGroupId);
                return AreaGroupRankTherionChallege.getRank(areaGroupBean, therionType);
            case TherionModule.THERION_WORLD:
                areaGroupBean = AreaGroupBean.get(areaIdOrGroupId);
                return WorldRankTherionChallege.getRank(areaGroupBean, therionType);
            default:
                return null;
        }
    }


    public static void update(TherionModule module, int gameType, int therionType, int areaIdOrGroupId) {

        DateTime now = DateTime.now();
        int dayOfWeek = now.getDayOfWeek(); //本周的第几天
        int[] conditions = module.getConditions(); //玩法开启时间，每周的哪一天
        DateTime handleTime = ActiveUtil.time03_00(now); //执行结束时间
        DateTime startTime = ActiveUtil.time08_00(now); //开始时间，当天的8.
        DateTime endTime = ActiveUtil.time22_00(now); //结束时间，当天的22.

        if (handleTime.isBefore(now)) return;

        ArrayList<Integer> areaList = new ArrayList<>();
        switch (gameType) {
            case TherionModule.THERION_LOCAL:
                areaList.add(areaIdOrGroupId);
                break;
            default:
                AreaGroupBean areaGroupBean = AreaGroupBean.get(areaIdOrGroupId);
                for (int i = 0; i < areaGroupBean.getAreaList().size(); i++) {
                    areaList.add(Integer.parseInt(areaGroupBean.getAreaList().get(i)));
                }
        }

        //重置
        if (ArrayUtils.contains(conditions, dayOfWeek)) {
            module.setOpenTime(startTime);
            module.setEndTime(endTime);
            module.setNeedSettle(false);
            TherionHandle.clearRandkAndInfo(areaIdOrGroupId, gameType, therionType);//清缓存
            Map<String, therionboss> allData = DataCenter.getAllData(therionboss.class);
            for (therionboss therionboss : allData.values()) {
                if (therionboss.getType() == gameType && therionboss.getName().equals(module.getName())) {
                    module.setLife(TherionModule.getLife(therionboss, areaList));
                    module.setTotalLife(TherionModule.getLife(therionboss, areaList));
                    break;
                }
            }
        } else {
            module.setOpen(false);
        }

        module.set(gameType, therionType, areaIdOrGroupId);
    }

}
